<template>
    <el-row :gutter="10">

        <!--左侧添加商品-->
        <el-col :span="12">
            <div>
                <!--顶部查询商品编号-->
                <el-input v-model="MerchandiseSearchInput" style="width: 240px" placeholder="按商品编号搜索" :prefix-icon="Search"/>
                
                <!--商品列表-->
                <el-table :data="GetMerchandiseData" border style="width: 100%; margin-top: 10px;">
                    <el-table-column prop="merchandiseId" label="商品编号" align="center" v-if="false"/>
                    <el-table-column prop="merchandiseName" label="商品名称" align="center"/>
                    <el-table-column prop="merchandisePrice" label="商品单价" align="center">
                        <template #default="{ row }">
                            ¥{{ row.merchandisePrice.toFixed(2) }}
                        </template>
                    </el-table-column>
                    <el-table-column label="添加商品" align="center">
                        <template #default="{ row }">
                            <el-button type="primary" size="small" @click="addProductToCart(row)">添加</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </el-col>

        <!--右侧显示清单-->
        <el-col :span="12">

            <!--销售信息-->
            <el-card center>
                <el-descriptions border column="1" label-width="50%">
                    <el-descriptions-item label="商品数量" label-align="center" align="center">{{ CartList.itemCount }}</el-descriptions-item>
                    <el-descriptions-item label="购买金额" label-align="center" align="center">{{ CartList.totalAmount }}</el-descriptions-item>
                </el-descriptions>
                <div style="margin-top: 10px; display: flex; justify-content: center;">
                    <el-button type="primary" @click="generateOrder">生成订单</el-button>
                    <el-button type="danger" @click="resetCart">清空列表</el-button>
                </div>
            </el-card>

            <!--购物车-->
            <div style="margin-top: 10px;">
                <el-table :data="CartList.items" border style="width: 100%;">
                    <el-table-column prop="merchandiseName" label="商品名称" align="center"/>
                    <el-table-column prop="merchandisePrice" label="商品单价" align="center">
                        <template #default="{ row }">
                            ¥{{ row.merchandisePrice.toFixed(2) }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="merchandiseQuantity" label="数量" align="center">
                        <template #default="{ row, $index }">
                            <el-input-number v-model="CartList.items[$index].merchandiseQuantity" :min="1" size="small" @change="calculateTotal" style="width:auto;" />
                        </template>
                    </el-table-column>
                    <el-table-column prop="merchandiseTotolPrice" label="金额" align="center">
                        <template #default="{ row }">
                            ¥{{ (row.merchandisePrice * row.merchandiseQuantity).toFixed(2) }}
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" align="center">
                        <template #default="{ $index }">
                            <el-button type="danger" size="small" @click="removeProductFromCart($index)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </el-col>
    </el-row>

</template>

<script lang='ts' setup name='Cashier'>

// 导入必要组件
import axios from 'axios';
import { reactive, ref, onMounted, watch, computed } from 'vue';
import { ElNotification, ElMessage } from 'element-plus'
import { Search } from '@element-plus/icons-vue'

// 生命周期钩子，组件挂载后初始化数据
onMounted(async () => {
    await GetMerchandise()
    calculateTotal()
})

// 购物车列表
let CartList = ref({
    items: [
        {
            merchandiseId: 13,              // 商品编号
            merchandiseName: "123",         // 商品名称
            merchandisePrice: 12,           // 商品单价
            merchandiseQuantity: 1,         // 商品数量
            merchandiseTotolPrice: 12       // 商品总价 = 商品单价 * 商品数量
        },
    ],
    itemCount: 0,
    totalAmount: 0
})

// 订单信息
let SalesData = ref({
    SalesID: 0,					// 销售记录编号（后端生成）
    SalesDate: 0,		        // 销售记录日期时间（后端生成）
    SalesPrice: 0,				// 销售记录总价（后端计算）
    SalesState: "已完成",		 // 销售记录状态
    // SalesEmployeesName: "",		// 操作员工姓名         // 删了
    // SalesMembershipID: 0,		// 会员编号（非必须）    // 删了
    // Employee_EmployeeID: 0,		// 操作员工编号         // 删了
})

// 订单商品
let ItemData = ref()

// 添加商品到当前订单
function addProductToCart(product: any){

    // 是否已在购物车查询
    const existingItem = CartList.value.items.find((item: any) => item.merchandiseId === product.merchandiseId)
    if (existingItem) {
        existingItem.merchandiseQuantity += 1
    } 
    else {
        CartList.value.items.push({
            merchandiseId: product.merchandiseId,
            merchandiseName: product.merchandiseName,
            merchandisePrice: product.merchandisePrice,
            merchandiseQuantity: 1,
            merchandiseTotolPrice: product.merchandisePrice
        })
    }
    calculateTotal()
}

// 从当前订单中移除商品
function removeProductFromCart(index: number){
    CartList.value.items.splice(index, 1)
    calculateTotal()
}

// 重置订单商品
function resetCart(){
    CartList.value.items = []
    calculateTotal()
}

// 计算总金额和商品件数
const calculateTotal = () => {
    CartList.value.itemCount = CartList.value.items.reduce((total: number, item: any) => total + item.merchandiseQuantity, 0)
    CartList.value.totalAmount = CartList.value.items.reduce((total: number, item: any) => total + (item.merchandisePrice * item.merchandiseQuantity), 0)
}

// 生成订单
function generateOrder(){

    // 空订单
    if (CartList.value.items.length === 0) {
        ElMessage.warning('请先添加商品到订单')
        return
    }

    // 处理数据
    SalesData.value.SalesPrice = CartList.value.totalAmount
    ItemData.value = CartList.value.items
    
    for(let i = 0; i<ItemData.value.length; i++){
        ItemData.value[i].merchandiseTotolPrice = ItemData.value[i].merchandiseQuantity * ItemData.value[i].merchandisePrice
    }

    ElMessage.success('订单生成成功')

    PostSales()
}

// GET ------------------------------------------ GET //

// GET: 获取的商品列表
const GetMerchandiseData = ref([
    {merchandiseId: 1223, merchandiseName: "123", merchandisePrice: 123},
    {merchandiseId: 1233, merchandiseName: "1223", merchandisePrice: 1233},
    {merchandiseId: 1243, merchandiseName: "1233", merchandisePrice: 1223},
])

// GET: 获取商品列表
async function GetMerchandise() {
    try {
        const response = await axios.get("/api/merchandise")
        console.log('获取商品列表成功:', response.data)
        GetMerchandiseData.value = response.data.data || []
    } catch (error) {
        ElNotification({
            title: '错误',
            message: '请求商品列表失败: ' + error,
            type: 'error',
        })
        console.error('获取商品列表失败:', error)
    }
}

// GET: 发送请求获得当前搜索商品的数据
async function GetMerchandiseById(){
	try{
		let MerchandiseData = await axios.get(`/api/merchandise/${MerchandiseSearchInput}`)
		GetMerchandiseData.value = MerchandiseData.data.data
	} catch(error){
		ElNotification({
			title: '错误',
			message: '单个商品数据请求失败\n'+error,
			type: 'error',
		})
	}
}

// 输入框接收到的商品编号
let MerchandiseSearchInput = ref('')

// 随时查询
watch(
	MerchandiseSearchInput, (New, Old) => {
		GetMerchandiseById()
	}
)

// POST ------------------------------------------ POST //

// POST: 添加的销售记录
let PostSalesData = ref({
    salesID: 0,					// 销售记录编号（后端生成）
    salesDate: 0,		        // 销售记录日期时间（后端生成）
    salesPrice: 0,				// 销售记录总价（后端计算）
    salesState: "已完成",		 // 销售记录状态
    itemList: ItemData
})

// POST: 添加销售记录
async function PostSales() {
    try {

        // 数据 todo...
        const response = await axios.post(
            "/api/sales",
        )
        ElNotification({
            title: '成功',
            message: '添加销售记录成功',
            type: 'success',
        })
        await GetMerchandise()
        resetCart()
    } catch (error) {
        ElNotification({
            title: '错误',
            message: '新增失败: ' + error,
            type: 'error',
        })
        console.error('新增销售记录失败:', error)
    }

    GetMerchandise()
}

</script>

<style scoped>

/* 表格居中设置 */
.el-table-column {
    text-align: center;
}

</style>